#include "myobject.h"
#include "Conf.h"
#include "CMemoryFile.h"
using namespace io;

namespace fireplane
{
	Conf::Conf(){}
	Conf::~Conf(){}

	const char* _all_conf_file[] = {
		"conf/level0/npc.conf"
	};

	void Conf::loadConf( int level ){
		unsigned long size;
		unsigned char* buffer = CCFileUtils::sharedFileUtils()->getFileData(_all_conf_file[level],"rb",&size);

		CMemoryFile* file = createMemoryReadFile(buffer,size,_all_conf_file[level],true);
		_loadConfFile(file);
	}

	void Conf::_loadConfFile(CMemoryFile* file){
		int i = 0;
		int ret = 1;
		char buf[256] ={0};
		char temp;
		char *pName = NULL, *pValue = NULL;
		while (ret)
		{	
			ret  = file->read(&temp,1);
			if(!ret || (temp =='#')) temp = '\n';
			if(temp != '\n') {
				buf[i++] = temp;
			}
			else if(i){
				buf[i] = '\0';
				i = 0;

				pName = buf;
				if((pValue = strchr(pName,'=')) == NULL)
					continue;
				*pValue++='\0'; 
				pName = trimString(pName);
				pValue = trimString(pValue);

				if(pName && pValue){
					char* itemName = (char*)malloc(strlen(pName));
					char* itemValue = (char*)malloc(strlen(pValue));
					if(itemName && itemValue) {
						strcpy(itemName,pName);
						strcpy(itemValue,pValue);
						_all_conf_map.insert(make_pair(itemName,itemValue));
					}
				}
			}
		}
	}

	int Conf::getInt(string name)
	{
		string strValue;
		ConfMap::iterator it = _all_conf_map.find(name);
		if(it != _all_conf_map.end()) {	
			strValue = it->second;

			return atoi(strValue.c_str());
		}

		return 0;
	}

	string Conf::getStr(string name)
	{
		string strValue;
		ConfMap::iterator it = _all_conf_map.find(name);
		if(it != _all_conf_map.end()) {			
			strValue = it->second;
			return strValue;
		}

		return NULL;
	}

	float Conf::getFloat(string name)
	{
		string strValue;
		ConfMap::iterator it = _all_conf_map.find(name);
		if(it != _all_conf_map.end()) {			
			strValue = it->second;
			return atof(strValue.c_str());
		}

		return 0.0f;
	}


	char* Conf::_trimLeft(char *str)
	{
		int len = 0, i = 0;

		if (str == NULL)
			return NULL;

		len = strlen(str);
		for(i = 0; i < len; i++){
			if (str[i] > ' '){
				break;
			}
		}

		if (i == len){
			str[0] = 0;
			return str;
		}
		else
			return str+i;
	}

	char* Conf::_trimRight(char *str)
	{
		int len = 0, i = 0;

		if (str == NULL)
			return NULL;

		len = strlen(str);
		for (i = len - 1; i >= 0; i--){
			if (str[i] >  ' ')
				break;
		}

		if (i == -1)
			str[0] = 0;
		else
			str[i+1] = 0;

		return str;
	}

	char* Conf::trimString(char *str)
	{
		char *tmp = NULL;

		tmp = _trimLeft(str);
		if (tmp)
			tmp = _trimRight(tmp);
		return tmp;
	}

	Conf* Conf::getConf()
	{
		if(!_s_Conf){
			_s_Conf = new Conf();
		}

		return _s_Conf;
	}

	Conf* Conf::_s_Conf = NULL;
}